const { defineConfig } = require('@vue/cli-service')
const bodyParer = require('body-parser')
const Mock = require('mockjs')

const data = Mock.mock({
  'list|50': [
    {
      'id|+1': 1,
      city: '@city',
      img: '@image(100x100, @color)',
      check: false,
      date: '@datetime',
    },
  ],
})

module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    setupMiddlewares(middlewares, { app }) {
      // app express服务器
      app.use(bodyParer.json())

      // 登陆
      app.post('/api/login', (req, res) => {
        const { username, password } = req.body
        res.send({
          code: 0,
          msg: 'sucess',
          data: {
            token: `${username}_admin`,
          },
        })
      })

      // 列表
      app.get('/api/list', (req, res) => {
        const { page = 1, size = 10 } = req.query
        // slice / filter
        res.send({
          code: 0,
          msg: 'success',
          data: {
            list: data.list.slice((page - 1) * size, page * size),
            total: data.list.length,
          },
        })
      })

      // 添加接口
      app.post('/api/addItem', (req, res) => {
        const addItem = req.body
        // slice / filter
        data.list.push({
          id: Date.now(),
          ...addItem,
        })
        res.send({
          code: 0,
          msg: '添加成功',
          data: data.list.length,
        })
      })

      // 编辑
      app.post('/api/editItem', (req, res) => {
        const editItem = req.body
        // slice / filter
        const editIndex = data.list.findIndex((v) => v.id == editItem.id)
        // 删除 list.splice(index, 1)
        // 替换 list.splice(index, 0, item)
        data.list.splice(editIndex, 1, editItem)
        res.send({
          code: 0,
          msg: '编辑成功',
        })
      })
      // 删除
      app.get('/api/deleteItem', (req, res) => {
        const { id } = req.query // =[1.2.3.4.]
        // slice / filter
        const removeIndex = data.list.findIndex((v) => v.id == id)
        // 删除 list.splice(index, 1)
        // 替换 list.splice(index, 0, item)
        data.list.splice(removeIndex, 1)
        res.send({
          code: 0,
          msg: '删除成功',
        })
      })

      return middlewares
    },
    // js  ---> json ---->   js ->  json

    // get url传递参数 ?key=value&key1=value1
    // axios.get('/api/list', {params: {...}})

    // post 请求体传参数
  },
})
